#include "inputwindow.h"
#include <QMainWindow>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QComboBox>
#include <QDateEdit>
#include <QVBoxLayout>
#include <QMessageBox>
#include <QDate>
#include <QFile>
#include <QTextStream>
#include <QIODevice>
#include <QCoreApplication>
#include <QDebug>
#include <QVBoxLayout>
#include <QLabel>
#include <QMessageBox>
#include <QDate>
#include <QFile>
#include <QTextStream>
#include <QIODevice>
#include <QCoreApplication>
#include <QDebug>

InputWindow::InputWindow(const QString &username, QWidget *parent) : 
    QMainWindow(parent), username(username)
{
    setWindowTitle("✨ BMI计算器 - 输入数据 ✨");
    resize(600, 500);
    setStyleSheet("background-color: #f8f9fa;");

    QLabel *titleLabel = new QLabel("📝 请输入您的健康数据", this);
    titleLabel->setStyleSheet(
        "font-size: 20pt; "
        "font-weight: bold; "
        "color: #6c757d; "
        "font-family: 'Microsoft YaHei';"
    );

    QLabel *heightLabel = new QLabel("📏 身高 (cm):", this);
    heightLabel->setStyleSheet("font-size: 14pt; color: #495057;");
    heightInput = new QLineEdit(this);
    heightInput->setPlaceholderText("请输入身高");
    heightInput->setStyleSheet(
        "QLineEdit {"
        "  font-size: 14pt;"
        "  padding: 10px;"
        "  border: 2px solid #dee2e6;"
        "  border-radius: 15px;"
        "  background-color: white;"
        "}"
    );

    QLabel *weightLabel = new QLabel("⚖️ 体重 (kg):", this);
    weightLabel->setStyleSheet("font-size: 14pt; color: #495057;");
    weightInput = new QLineEdit(this);
    weightInput->setPlaceholderText("请输入体重");
    weightInput->setStyleSheet(
        "QLineEdit {"
        "  font-size: 14pt;"
        "  padding: 10px;"
        "  border: 2px solid #dee2e6;"
        "  border-radius: 15px;"
        "  background-color: white;"
        "}"
    );

    QLabel *ageLabel = new QLabel("🎂 年龄 (选填):", this);
    ageLabel->setStyleSheet("font-size: 14pt; color: #495057;");
    ageInput = new QLineEdit(this);
    ageInput->setPlaceholderText("请输入年龄");
    ageInput->setStyleSheet(
        "QLineEdit {"
        "  font-size: 14pt;"
        "  padding: 10px;"
        "  border: 2px solid #dee2e6;"
        "  border-radius: 15px;"
        "  background-color: white;"
        "}"
    );

    QLabel *genderLabel = new QLabel("👫 性别 (选填):", this);
    genderLabel->setStyleSheet("font-size: 14pt; color: #495057;");
    genderInput = new QComboBox(this);
    genderInput->addItems({"男", "女"});
    genderInput->setCurrentIndex(-1);
    genderInput->setStyleSheet(
        "QComboBox {"
        "  font-size: 14pt;"
        "  padding: 10px;"
        "  border: 2px solid #dee2e6;"
        "  border-radius: 15px;"
        "  background-color: white;"
        "}"
    );

    // 添加日期选择控件
    QLabel *dateLabel = new QLabel("📅 记录日期:", this);
    dateLabel->setStyleSheet("font-size: 14pt; color: #495057;");
    dateInput = new QDateEdit(QDate::currentDate(), this);
    dateInput->setCalendarPopup(true);
    dateInput->setDisplayFormat("yyyy-MM-dd");
    dateInput->setStyleSheet(
        "QDateEdit {"
        "  font-size: 14pt;"
        "  padding: 10px;"
        "  border: 2px solid #dee2e6;"
        "  border-radius: 15px;"
        "  background-color: white;"
        "}"
    );

    calculateBtn = new QPushButton("✨ 计算BMI", this);
    calculateBtn->setStyleSheet(
        "QPushButton {"
        "  font-size: 14pt;"
        "  padding: 12px 24px;"
        "  background-color: #4cc9f0;"
        "  color: white;"
        "  border-radius: 15px;"
        "  border: none;"
        "}"
        "QPushButton:hover {"
        "  background-color: #4895ef;"
        "}"
    );

    // 历史记录按钮
    historyBtn = new QPushButton("📜 查看历史记录", this);
    historyBtn->setStyleSheet(
        "QPushButton {"
        "  font-size: 14pt;"
        "  padding: 12px 24px;"
        "  background-color: #f72585;"
        "  color: white;"
        "  border-radius: 15px;"
        "  border: none;"
        "}"
        "QPushButton:hover {"
        "  background-color: #b5179e;"
        "}"
    );
    
    connect(historyBtn, &QPushButton::clicked, [this]() {
        showHistory();
    });

    connect(calculateBtn, &QPushButton::clicked, [this]() {
        bool ok;
        double height = heightInput->text().toDouble(&ok);
        if (!ok || height <= 0) {
            QMessageBox::warning(this, "错误", "请输入有效的身高");
            return;
        }

        double weight = weightInput->text().toDouble(&ok);
        if (!ok || weight <= 0) {
            QMessageBox::warning(this, "错误", "请输入有效的体重");
            return;
        }

        int age = ageInput->text().toInt();
        QString gender = genderInput->currentIndex() >= 0 ? genderInput->currentText() : "";

        emit dataSubmitted(height, weight, age, gender, dateInput->date());
    });

    QVBoxLayout *layout = new QVBoxLayout();
    layout->addWidget(titleLabel);
    layout->addWidget(heightLabel);
    layout->addWidget(heightInput);
    layout->addWidget(weightLabel);
    layout->addWidget(weightInput);
    layout->addWidget(ageLabel);
    layout->addWidget(ageInput);
    layout->addWidget(genderLabel);
    layout->addWidget(genderInput);
    layout->addWidget(dateLabel);
    layout->addWidget(dateInput);
    layout->addWidget(calculateBtn);
    layout->addWidget(historyBtn);
    
    // 加载历史记录
    loadRecords();
    layout->addStretch();

    QWidget *centralWidget = new QWidget(this);
    centralWidget->setLayout(layout);
    setCentralWidget(centralWidget);
}

void InputWindow::saveRecord(double height, double weight, int age, const QString &gender, const QDate &date, double bmi)
{
    Record record;
    record.date = date.toString("yyyy-MM-dd");
    record.height = height;
    record.weight = weight;
    record.age = age;
    record.gender = gender;
    record.bmi = bmi;
    
    records.append(record);
    
    // 简单实现：将记录保存到文件
    QFile file(QCoreApplication::applicationDirPath() + "/" + username + "_records.txt");
    if (file.open(QIODevice::WriteOnly | QIODevice::Append)) {
        QTextStream stream(&file);
        stream << record.date << ","
               << record.height << ","
               << record.weight << ","
               << record.age << ","
               << record.gender << ","
               << record.bmi << "\n";
        file.close();
    }
}

void InputWindow::loadRecords()
{
    QString filePath = QCoreApplication::applicationDirPath() + "/" + username + "_records.txt";
    qDebug() << "尝试加载历史记录文件:" << filePath;
    
    QFile file(filePath);
    
    // 如果文件不存在则创建空文件
    if (!file.exists()) {
        qDebug() << "文件不存在，尝试创建新文件";
        if (file.open(QIODevice::WriteOnly)) {
            file.close();
            qDebug() << "成功创建空记录文件";
        } else {
            qDebug() << "创建文件失败:" << file.errorString();
            QMessageBox::warning(this, "警告", 
                QString("无法创建历史记录文件:%1错误: %2")
                .arg(filePath)
                .arg(file.errorString()));
        }
        return;
    }

    if (file.open(QIODevice::ReadOnly)) {
        qDebug() << "成功打开历史记录文件";
        QTextStream stream(&file);
        while (!stream.atEnd()) {
            QString line = stream.readLine();
            QStringList parts = line.split(",");
            if (parts.size() == 6) {
                Record record;
                record.date = parts[0];
                record.height = parts[1].toDouble();
                record.weight = parts[2].toDouble();
                record.age = parts[3].toInt();
                record.gender = parts[4];
                record.bmi = parts[5].toDouble();
                records.append(record);
            }
        }
        file.close();
        qDebug() << "成功加载" << records.size() << "条历史记录";
    } else {
        qDebug() << "打开文件失败:" << file.errorString();
        QMessageBox::warning(this, "警告", 
            QString("无法读取历史记录文件:%1错误: %2")
            .arg(filePath)
            .arg(file.errorString()));
    }
}

void InputWindow::showHistory()
{
    QString historyText = "📅 您的历史记录:\n\n";
    for (const Record &record : records) {
        historyText += QString("📌 %1\n"
                              "  身高: %2 cm\n"
                              "  体重: %3 kg\n"
                              "  BMI: %4\n"
                              "  年龄: %5\n"
                              "  性别: %6\n\n")
                          .arg(record.date)
                          .arg(record.height)
                          .arg(record.weight)
                          .arg(record.bmi, 0, 'f', 1)
                          .arg(record.age > 0 ? QString::number(record.age) : "未填写")
                          .arg(record.gender.isEmpty() ? "未填写" : record.gender);
    }
    
    QMessageBox::information(this, "历史记录", historyText);
}
